package com.zihan.service;

import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Map;

@Service
public class CertificateGeneratorService {

    // 渲染HTML模板
    private String renderHtmlTemplate(String templatePath, Map<String, String> data) throws IOException {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(templatePath);
        if (inputStream == null) {
            throw new IOException("找不到模板文件: " + templatePath);
        }
        String html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
        for (Map.Entry<String, String> entry : data.entrySet()) {
            html = html.replace("{{" + entry.getKey() + "}}", entry.getValue());
        }
        return html;
    }

    // 生成PDF
    public File generatePdf(String name, String activityName) throws Exception {
        String date = LocalDate.now().toString();
        Map<String, String> data = Map.of("name", name, "activityName", activityName, "date", date);
        String html = renderHtmlTemplate("certificate.html", data);
        
        // 确保HTML是完整的XHTML格式
        String xhtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " +
                "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
                "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                "<head><meta charset=\"UTF-8\"/><title>Certificate</title></head>" +
                "<body>" + html + "</body></html>";
        
        File pdfFile = File.createTempFile("certificate_", ".pdf");
        
        // 使用 Flying Saucer 生成 PDF，非常稳定
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(xhtml);
            renderer.layout();
            renderer.createPDF(fos);
        }
        
        return pdfFile;
    }
}
